<template>
  <div>
    <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="onClickLeft" fixed />
     <!-- 商品区域 -->
    <div class="shop_box">
      <!-- 复选框组 -->
      <van-checkbox-group v-model="result">
        <!-- 滑动单元格 -->
        <van-swipe-cell v-for="(item,index) in cartList" :key="index">
          <!-- 布局 -->
          <van-row>
            <!-- 复选框 -->
            <van-col span="2">
              <van-checkbox :name="item" @click="chenekbox"></van-checkbox>
            </van-col>
            <!-- 商品卡片 -->
            <van-col span="22">
              <van-card
                :price="item.list.actualPrice"
                :desc="item.list.desc"
                :origin-price="item.list.originalPrice"
                :title="item.list.dtitle"
                :thumb="item.list.mainPic"
              >
                <!-- 计步器 -->
                <template #footer>
                  <van-stepper v-model="item.count" @click="NUMchecked"/>
                </template>
              </van-card>
            </van-col>
          </van-row>
          <!-- 删除 -->
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="del(index)" />
          </template>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>
    <!-- 提交区 -->
    <van-submit-bar :price="pricebox*100" button-text="提交订单">
      <van-checkbox v-model="checked" @click="addbox">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      checked: false,
      cartList: [],
      result:[],
    };
  },
  created() {
    let cartList = localStorage.cartList;
    if (cartList != undefined) {
      this.cartList = JSON.parse(cartList);
    }
  },
  computed: {
    // 总价
    pricebox() {
      let mouny = 0;
      this.result.map(a => {
        mouny += a.list.actualPrice * a.count;
      });
      return mouny;
    }
  },
  methods: {
    onClickLeft() {
      window.history.back();
    },
    // 删除
    del(i) {
      // 获取删除的
      let del = this.cartList.splice(i, 1);
      //  console.log(del);
      // 看选中的和本身数组中的id
      this.result.map((item, a) => {
        if (item.list.id == del[0].list.id) {
          //  一样的话删除
          this.result.splice(a, 1);
        }
      });
       this.save();
    },
    // 查看是否为全选
    chenekbox() {
      if (this.result.length == this.cartList.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    // 全选不全选
    addbox() {
      if (this.checked) {
        // 空的等于我本地全部的
        this.result = this.cartList;
      } else {
        this.result = [];
      }
    },
    save(){
      localStorage.cartList = JSON.stringify(this.cartList)
    },
    // 计步器
    NUMchecked(){
      this.save()
    }
  }
};
</script>

<style scoped>
.shop_box {
  margin-top: 48px;
}
.goods-card {
  margin: 0;
  background-color: @white;
}
.delete-button {
    height: 100%;
  }
</style>